import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lcapp/api/interface/zixun_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/data/zixun_data_entity.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/refresh/refresh.dart';
import 'package:lcapp/page/home/home_zixun_item.dart';

class HomeZXListPage extends StatefulWidget {
  final int typeId;
  final int vipFlag;
  const HomeZXListPage({Key? key, required this.typeId, this.vipFlag=0}) : super(key: key);

  @override
  _HomeZXListPageState createState() => _HomeZXListPageState();
}

class _HomeZXListPageState extends State<HomeZXListPage> {

  List<ZixunDataEntity> zixuns = [];
  int pageNum = 1;
  int pageSize = 10;
  late StreamSubscription loginSub;
  late StreamSubscription _subscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loginSub = eventBus.on<LoginState>().listen((event) {
      setState(() {});
    });
    _subscription = eventBus.on<PayState>().listen((event) {
      if (event.state == 0) {
        setState(() {});
      }
    });
    getZixun();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    loginSub.cancel();
    _subscription.cancel();
  }

  getZixun()async{
    ResponseData res = await ZiXunAPI.getZiXunList(pageNum, pageSize,articleTypeId: widget.typeId,vipFlag: widget.vipFlag??0);
    if(res.code==200){
      if(pageNum==1){
        zixuns.clear();
      }
      List arr = res.data??[];
      for (var e in arr) {
        ZixunDataEntity entity = ZixunDataEntity().fromJson(e);
        zixuns.add(entity);
      }
    }
    if(mounted){setState(() {
    });}
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 30.w,right: 30.w,top: 30.w),
      child: EasyRefresh(
        header: myRefreshHeader(),
        footer: myRefreshFooter(),
        onRefresh: ()async{
          pageNum=1;
          getZixun();
        },
        onLoad: ()async{
          pageNum++;
          getZixun();

        },
        child:
        ListView.builder(
            padding: EdgeInsets.zero,
            shrinkWrap: true,
            itemCount: zixuns.length,
            itemBuilder: (BuildContext context, int i) {
              return HomeZixunItem(entity: zixuns[i],);
            }),
      ),
    );
  }
}
